// pages/book/detail/index.js
import { BookModel } from '../../../models/book.js'
import { LikeModel } from '../../../models/like.js'

const bookModel = new BookModel()
const likeModel = new LikeModel()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments: [],
    book:null,
    likeStatus: false,
    likeCount: 0,
    posting: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    const { bid } = options
    const detail = bookModel.getDetail(bid)
    const comments = bookModel.getComments(bid)
    const likeStatus = bookModel.getLikeStatus(bid)

    Promise.all([detail, comments, likeStatus]).then(res => {
      this.setData({
        book:res[0],
        comments: res[1].comments,
        likeStatus: res[2].like_status,
        likeCount: res[2].fav_nums
      })
      wx.hideLoading()
    })
  },

  onLike: function(evt) {
    const bid = this.data.book.id
    const likeOrCancel = evt.detail.behavior
    likeModel.like(likeOrCancel, bid, 400)
  },

  onFakePost: function(evt) {
    this.setData({ posting: true })
  },

  onCancel: function(evt) {
    this.setData({ posting: false })
  },

  onPost:function(evt) {
    const comment = evt.detail.text || evt.detail.value
    if(!comment) return;
    if (comment.lenght > 12) {
      wx.showToast({
        title: '短评最多12个字',
        icon:'none'
      })
      return
    }

    bookModel.postComment(this.data.book.id, comment).then(res => {
      wx.showToast({
        title: '+ 1',
        icon:'none'
      })

      this.data.comments.unshift({
        content: comment,
        nums: 1
      })

      this.setData({
        comments: this.data.comments,
        posting: false
      })
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})